const { contextBridge, ipcRenderer } = require('electron');
const log = require('electron-log');
const crypto = require('crypto');
const path = require('path')

log.transports.file.format = '[{y}-{m}-{d} {h}:{i}:{s}.{ms}] [{level}] {text}'

const validChannels = ['ipc-example', 'user-info', 'download-ts-reply', 'will-close'];

contextBridge.exposeInMainWorld('electron', {
  ipcRenderer: {
    myPing() {
      ipcRenderer.send('ipc-example', 'ping');
    },
    on(channel, func) {
      if (validChannels.includes(channel)) {
        // Deliberately strip event as it includes `sender`
        ipcRenderer.on(channel, (event, ...args) => func(...args));
      }
    },
    once(channel, func) {
      const validChannels = ['ipc-example'];
      if (validChannels.includes(channel)) {
        // Deliberately strip event as it includes `sender`
        ipcRenderer.once(channel, (event, ...args) => func(...args));
      }
    },
    // 关闭app
    exit() {
      ipcRenderer.send('exit-app')
    },
    login() {
      ipcRenderer.send('open-login')
    },
    // removeLogin() {
    //   ipcRenderer.send('remove-login')
    // }

    getStoreValue(key) {
      return ipcRenderer.invoke('get-store-value', key)
    },
    setStoreValue(key, data) {
      ipcRenderer.send('set-store-value', {key, data})
    },

    getLocalConfig() {
      return ipcRenderer.invoke('get-local-config')
    },

    /** 下载 m3u8 文件 */
    startDownloadM3U8({url, filePath, fileName}) {
      // console.log('start-download =', url)
      return ipcRenderer.invoke('start-download-m3u8', {url, filePath, fileName})
    },
    /** 下载 ts 文件 */
    startDownloadTS({url, filePath, taskId, name}) {
      ipcRenderer.send('start-download-ts', {url, filePath, taskId, name})
    },

    // 获取保存地址
    setSavePath(savePath) {
      return ipcRenderer.invoke('set-save-path', savePath)
    },

    // 删除课程
    deleteM3U8(filePath) {
      ipcRenderer.send('delete-directory', filePath)
    },

    // 获取本地目录
    getDirectory() {
      return ipcRenderer.invoke('get-directory')
    },

    // 写入课程文件
    writeTask(task) {
      ipcRenderer.send('write-task', task)
    },

    // 导入本地课程
    importLocalCourse(dirPath){
      return ipcRenderer.invoke('import-course', dirPath)
    },

    // 设置本地服务静态资源路径
    setStaticPath(staticPath){
      ipcRenderer.send('set-server-static-path', staticPath)
    }


  },

  log: log.functions,

  crypto: {
    md5(info) {
      return crypto.createHash('md5').update(String(info)).digest('hex')
    }
  },
  path: path

});

contextBridge.exposeInMainWorld('nodeModule', {
  // Store: store
})
